"""
File   : 03_response_format.py
Desc   : 结构化输出 response_format——JSON Schema
Date   : 2024/11/27
Author : Tianyu Chen
https://platform.openai.com/docs/guides/structured-outputs
"""


from openai import OpenAI
client = OpenAI()

response = client.chat.completions.create(
    model="gpt-4o-mini-2024-07-18",
    messages=[
        {
            "role": "system", 
            "content": "You extract email addresses"
        },
        {
            "role": "user", 
            "content": "Feeling stuck? Send a message to help@mycompany.com."
        }
    ],
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "email_schema",
            "schema": {
                "type": "object",
                "properties": {
                    "email": {
                        "description": "The email address that appears in the input",
                        "type": "string"
                    }
                },
                "required": ["email"],
                "additionalProperties": False
            },
            "strict": True
        }
    }
    #,stream=True  # 支持流式输出
)

print(response.choices[0].message.content)
""" output:
{"email":"help@mycompany.com"}
"""

# print(response)
"""
ChatCompletion(
    id='chatcmpl-AQ5J7y69Of0gPLF98ZDaMAAxal8l2', 
    choices=[
        Choice(
            finish_reason='stop', 
            index=0, 
            logprobs=None, 
            message=ChatCompletionMessage(
                content='{"email":"help@mycompany.com"}', 
                refusal=None, 
                role='assistant', 
                audio=None, 
                function_call=None, 
                tool_calls=None
            )
        )
    ], 
    created=1730780293, 
    model='gpt-4o-mini-2024-07-18', 
    object='chat.completion', 
    service_tier=None, 
    system_fingerprint='fp_0ba0d124f1', 
    usage=CompletionUsage(
        completion_tokens=9, 
        prompt_tokens=69, 
        total_tokens=78, 
        completion_tokens_details=CompletionTokensDetails(
            audio_tokens=None, 
            reasoning_tokens=0, 
            accepted_prediction_tokens=0, 
            rejected_prediction_tokens=0
        ), 
        prompt_tokens_details=PromptTokensDetails(
            audio_tokens=None, 
            cached_tokens=0
        )
    )
)
"""